package com.ziq.zcamp.post

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.Toast
import androidx.activity.viewModels
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.ziq.base.base.BaseActivity
import com.ziq.base.extension.binding
import com.ziq.base.extension.click
import com.ziq.zcamp.bean.place.CampListItem
import com.ziq.zcamp.bean.post.CampInfo
import com.ziq.zcamp.databinding.ActivitySelectLocationTabBinding
import com.ziq.zcamp.manager.DataManager.mHandler
import com.ziq.zcamp.util.KeyboardHelper
import com.ziq.zcamp.view.CustomLinePagerIndicator
import com.ziq.zcamp.view.OrderPagerTitleView
import dagger.hilt.android.AndroidEntryPoint
import net.lucode.hackware.magicindicator.FragmentContainerHelper
import net.lucode.hackware.magicindicator.buildins.UIUtil
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator

//选位置
@AndroidEntryPoint
class SelectLocationTabActivity : BaseActivity() {

    private val binding: ActivitySelectLocationTabBinding by binding()
    val mViewModel: SelectLocationTabViewModel by viewModels()

    companion object {
        const val SELECTED_CAMP = "camp"
        const val SELECTED_POI = "poi"
        const val TARGET_TAB_CAMP = 0
        const val TARGET_TAB_LOCATION = 1
        const val TITLE_CAMP = "营地"
        const val TITLE_LOCATION = "地点"
    }
    var initTabIndex = 0
    val titles = listOf<String>(
        TITLE_CAMP,
        TITLE_LOCATION
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        try {
            if(intent.hasExtra(SELECTED_POI)){
                mViewModel.poiItem.value = intent.getParcelableExtra(SELECTED_POI)
            }
            if(intent.hasExtra(SELECTED_CAMP)){
                mViewModel.campInfo.value = intent.getSerializableExtra(SELECTED_CAMP) as CampListItem?
            }
        }catch (e:Exception){
            println("$e")
        }
        binding.root
        binding.back.click {
            finish()
        }
        binding.complete.click {
            if(mViewModel.campInfo.value == null && mViewModel.poiItem.value == null){
                Toast.makeText(this, "请选择", Toast.LENGTH_SHORT).show()
            }else {
                val data = Intent()
                data.putExtra(SELECTED_CAMP, mViewModel.campInfo.value)
                data.putExtra(SELECTED_POI, mViewModel.poiItem.value)
                setResult(Activity.RESULT_OK, data)
                finish()
            }
        }
        binding.llSearch.click {
            binding.llSearch.visibility = View.GONE
            binding.llSearchInput.visibility = View.VISIBLE
            KeyboardHelper.showSoftInput(this, binding.searchInput)
        }
        binding.searchInput.setOnFocusChangeListener { v, hasFocus ->
            if(hasFocus){
                binding.llSearch.visibility = View.GONE
                binding.llSearchInput.visibility = View.VISIBLE
            } else {
                binding.llSearch.visibility = View.VISIBLE
                binding.llSearchInput.visibility = View.GONE
            }
        }
        binding.searchInput.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                mHandler.removeCallbacks(searchRunnable)
                mHandler.postDelayed(searchRunnable, 1000)
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })
        binding.searchInput.setOnEditorActionListener { _, actionId, _ ->
            if(actionId == EditorInfo.IME_ACTION_SEARCH){
                mHandler.removeCallbacks(searchRunnable)
                mHandler.postDelayed(searchRunnable, 0)
                return@setOnEditorActionListener true
            }
            return@setOnEditorActionListener false
        }

        initMagicIndicator()
        initViewPager()

        handleTabSelected(initTabIndex)
    }

    val searchRunnable = Runnable {
        mViewModel.keyword.value = binding.searchInput.text.toString()
    }


    private val mFragmentContainerHelper = FragmentContainerHelper()
    private fun initMagicIndicator() {
        val magicIndicator = binding.magicIndicator
        val commonNavigator = CommonNavigator(this)
        commonNavigator.notifyDataSetChanged()
        commonNavigator.isAdjustMode = true
        commonNavigator.adapter = object : CommonNavigatorAdapter() {
            override fun getCount(): Int {
                return titles.size
            }

            override fun getTitleView(context: Context, index: Int): IPagerTitleView {
                val simplePagerTitleView = OrderPagerTitleView(context)
                simplePagerTitleView.gravity = Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL
                simplePagerTitleView.text = titles[index]
                simplePagerTitleView.selectedColor = Color.parseColor("#333333")
                simplePagerTitleView.normalColor = Color.parseColor("#ABABAB")
                simplePagerTitleView.textSize = 14f
                simplePagerTitleView.setOnClickListener {
                    handleTabSelected(index)
                }
                return simplePagerTitleView
            }

            override fun getIndicator(context: Context): IPagerIndicator {
                val indicator = CustomLinePagerIndicator(context)
                indicator.mode = LinePagerIndicator.MODE_EXACTLY
                indicator.lineHeight = UIUtil.dip2px(context, 4.0).toFloat()
                indicator.lineWidth = UIUtil.dip2px(context, 30.0).toFloat()
                indicator.setColors(Color.parseColor("#AF8B6C"))
                return indicator
            }
        }
        magicIndicator.navigator = commonNavigator
        mFragmentContainerHelper.attachMagicIndicator(magicIndicator)
    }

    private fun initViewPager() {
        binding.viewPager.adapter = object : FragmentStateAdapter(this) {
            override fun getItemCount(): Int {
                return titles.size
            }

            override fun createFragment(position: Int): Fragment {
                return when(position){
                    TARGET_TAB_CAMP -> SelectLocationCampFragment()
                    TARGET_TAB_LOCATION -> SelectLocationPoiFragment()
                    else ->{
                        SelectLocationCampFragment()
                    }
                }
            }
        }
        binding.viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                handleTabSelected(position, isForViewPagerScroll = true)
            }
        })
        binding.viewPager.offscreenPageLimit = 2
        binding.viewPager.isUserInputEnabled = true
    }


    private var currentTabIndex = -1
    fun handleTabSelected(index: Int, isForViewPagerScroll: Boolean = false){
        if(currentTabIndex != index && index >= 0){
            currentTabIndex = index
            mFragmentContainerHelper.handlePageSelected(index)
            if(!isForViewPagerScroll){
                binding.viewPager.setCurrentItem(index, false)
            }
        }
    }
}